<template>
  <edit-card :title="'模型评估'" :confirm-text="'创建'" :type="'add'" :loading="loading" @confirm="confirmTask">
    <div class="edit-task">
      <a-form
        ref="taskFormRef"
        :model="formState"
        :rules="taskRules"
        :label-col="{ style: { width: '120px' } }"
        class="w-560"
        label-align="left"
      >
        <a-form-item label="任务名称" name="name">
          <div class="w-440">
            <a-input v-model:value="formState.name" v-trim placeholder="请输入任务名称" :disabled="!!taskId" :maxlength="200" />
          </div>
        </a-form-item>
        <div class="tag-select">
          <div class="left">
            <a-form-item label="来源" name="modelType">
              <a-radio-group v-model:value="formState.modelType" :disabled="!!taskId" :options="typeOptions" />
            </a-form-item>
          </div>
        </div>
        <div v-if="formState.modelType === 1">
          <a-form-item label="模型" name="modelInfoIdFavorite">
            <a-select
              v-model:value="formState.modelInfoIdFavorite"
              style="margin-right: 12px; width: 440px"
              :field-names="{ label: 'name', value: 'id' }"
              placeholder="请选择模型"
              :options="modelBaseOptions"
              @change="modelChange"
            />
          </a-form-item>
        </div>
        <div v-if="formState.modelType === 0" class="model-select">
          <a-form-item label="模型" name="model">
            <a-select
              v-model:value="formState.model"
              :style="{ 'margin-right': '12px', width: formState.modelType === 0 ? '214px' : '440px' }"
              :field-names="{ label: 'name', value: 'id' }"
              placeholder="请选择模型"
              :options="modelBaseOptions"
              @change="modelChange"
            />
          </a-form-item>
          <a-form-item label="" name="modelInfoId">
            <a-select
              v-model:value="formState.modelInfoId"
              :field-names="{ label: 'version', value: 'id' }"
              placeholder="请选择版本号"
              style="width: 214px"
              :options="versionOptions"
              @change="versionChange"
            />
          </a-form-item>
        </div>
        <a-form-item v-if="formState.modelType === 0" label="模型来源" name="source">
          <div class="w-440">
            <a-select v-model:value="formState.sourceName" v-trim disabled :options="sourceOptions" :maxlength="200" />
          </div>
        </a-form-item>
        <!-- <div v-if="formState.modelType === 1"> -->
        <!--
						0-"用户上传"
						1-"公开模型发布"
						2-"自定义模型发布"
						3-"我的算法发布"
						4-"预置算法发布"
					-->
        <a-form-item
          v-if="formState.source === 4 || formState.source === 1 || formState.modelType === 1"
          label="评估指标"
          name="normDetailsIdList"
        >
          <div class="w-440">
            <a-select
              v-model:value="formState.normDetailsIdList"
              mode="multiple"
              :field-names="{ label: 'name', value: 'id' }"
              placeholder="请选择评估指标"
              :options="normDetailsOptions"
            />
          </div>
        </a-form-item>
        <!-- </div> -->
        <div v-if="formState.modelType === 0">
          <a-form-item
            v-if="formState.source === 2 || formState.source === 3 || formState.source === 0"
            label="评估代码"
            name="codeFileUrl"
          >
            <file-upload
              v-model:file-url="formState.codeFileUrl"
              class="file-upload w-440"
              :max-count="1"
              :is-preview="false"
              accept="zip"
              suffix="zip"
              :module-custom-prefix="prefixUrl"
              :custom-prefix-name-has-unix="false"
              :max-file-size="200"
              @upload-success-after="fileUploadSuccess"
            >
              <a-button type="dashed" size="small" class="icon-with-btn btn-mini">
                <div class="upload-btn">
                  <img src="@/assets/img/upload-2-line-text02.svg" alt="" />
                  上传
                </div>
              </a-button>
            </file-upload>
          </a-form-item>
        </div>
        <a-form-item label="测试集" name="dataIdList">
          <div class="w-866">
            <g-select-tree-data
              ref="selectDataBucketRef"
              v-model:checked-ids="formState.dataIdList"
              type-name="数据集"
              :disabled="!!taskId"
              :get-tree-data-api="selectTreeDataApi.dataBucketTree"
              :get-collect-tree-data-api="selectTreeDataApi.collectDataBucketTree"
              :get-list-data-api="selectTreeDataApi.searchBucketList"
              :get-collect-list-data-api="selectTreeDataApi.collectSearchBucketList"
              :field-names="{ children: 'children', title: 'name', key: 'id' }"
              @change="changeData"
            />
          </div>
        </a-form-item>
      </a-form>
    </div>
  </edit-card>
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { onMounted, ref, watch } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute, useRouter } from 'vue-router'

  import GSelectTreeData from '@/components/GSelectTreeData/index.vue'
  import { modelEvaluationApi, selectTreeDataApi } from '@/services/api'
  import { validateBitLen, validateDirName } from '@/utils'

  import { sourceOptions, taskTypeArr } from '../options'

  interface form {
    dataIdList: string[]
    modelInfoIdFavorite: string
    name: string
    modelType: number
    codeFileUrl: string
    id: string
    modelBase: string
    sourceName: string
    normDetailsIdList: string[]
    modelInfoId: string
    [key: string]: any
  }

  const route = useRoute()
  const router = useRouter()

  const taskFormRef = ref()

  const taskId = route.params.id as string | ''
  const formState = ref<form>({
    name: '',
    dataIdList: [],
    modelBase: '',
    modelInfoId: '',
    modelType: 0,
    sourceName: '',
    id: '',
    modelInfoIdFavorite: '',
    source: '',
    normDetailsIdList: [],
    codeFileUrl: ''
  })

  let validateAckData = async (rule: Rule, value: string) => {
    if (value.length === 0) {
      return Promise.reject('请选择数据集')
    }

    return Promise.resolve()
  }
  const taskRules: Record<string, Rule[]> = {
    name: [
      { required: true, trigger: 'change', message: '请输入任务名称' },
      { validator: validateDirName() },
      { validator: validateBitLen(200), trigger: 'change' }
    ],
    dataIdList: [{ required: true, trigger: 'change', validator: validateAckData }],
    modelBase: [{ required: true, trigger: 'change', message: '请选择模型' }],
    modelType: [{ required: true, trigger: 'change', message: '请选择来源' }],
    modelInfoId: [{ required: true, trigger: 'change', message: '请选择版本' }],
    modelInfoIdFavorite: [{ required: true, trigger: 'change', message: '请选择模型' }],
    model: [{ required: true, trigger: 'change', message: '请选择模型' }],
    version: [{ required: true, trigger: 'change', message: '请选择版本' }],
    source: [{ required: true, trigger: 'change', message: '请选择模型来源' }],
    normDetailsIdList: [{ required: true, trigger: 'change', message: '请选择评估指标' }],
    codeFileUrl: [{ required: true, message: '请上传代码文件', trigger: 'change' }]
  }
  // 类型组
  const typeOptions = ref(taskTypeArr)
  //  模型
  const modelBaseOptions = ref<Record<string, any>[]>([])
  // 版本
  const versionOptions = ref<Record<string, any>[]>([])
  // 指标
  const normDetailsOptions = ref<Record<string, any>[]>([])

  // TODO: 数据集数据
  const selectDataBucketRef = ref<InstanceType<typeof GSelectTreeData>>()
  // 文件上传前缀prefixUrl
  const prefixUrl = ref<string>('/')

  // 初始化时获取文件前缀
  const initFilerefixUrl = async () => {
    const { data } = await modelEvaluationApi.uploadDir()
    formState.value.id = data.taskId
    prefixUrl.value = data.codeFileParentDir + '/'
  }
  // 获取公开模型
  const getModelBaseList = async () => {
    const { data } = await modelEvaluationApi.modelBaseList()
    modelBaseOptions.value = data
    console.log('modelBaseOptions', modelBaseOptions.value)
  }
  // 获取收藏模型
  const getModelFavoriteList = async () => {
    const { data } = await modelEvaluationApi.modelFavoriteList()
    modelBaseOptions.value = data
    console.log('modelBaseOptions', modelBaseOptions.value)
  }
  const modelChange = (value: any, option: any) => {
    versionOptions.value = option.infos
    if (formState.value.modelType === 1) {
      formState.value.modelInfoId = value
    } else {
      // formState.value.modelInfoId = ''
      formState.value.sourceName = ''
      formState.value.source = null
    }
  }
  const versionChange = (value: any, option: any) => {
    sourceOptions.forEach((item: any) => {
      if (item.value === option.source) {
        formState.value.sourceName = item.label
        formState.value.source = item.value
      }
    })
  }
  // 获取评估指标
  const getNormDetailsOptions = async () => {
    const { data } = await modelEvaluationApi.getNormDetailsOptions()
    normDetailsOptions.value = data
  }

  const changeData = (data: any) => {
    formState.value.dataIdList = data
  }

  const fileUploadSuccess = (file: any) => {
    formState.value.size = file.size
  }

  // TODO:确定
  const confirmTask = () => {
    taskFormRef.value
      .validate()
      .then(() => {
        submitForm()
      })
      .catch((err: any) => {
        console.log(err)
      })
  }

  const { loading, runAsync: runAddDataCleaning } = useRequest(modelEvaluationApi.add)

  const params = ref<any>({})
  const submitForm = async () => {
    // 模型管理
    if (formState.value.modelType === 0) {
      params.value.id = formState.value.id
      params.value.name = formState.value.name
      params.value.modelType = formState.value.modelType
      params.value.modelInfoId = formState.value.modelInfoId
      params.value.source = formState.value.source
      params.value.normDetailsIdList = formState.value.normDetailsIdList
      params.value.dataIdList = formState.value.dataIdList
      params.value.codeFileUrl = formState.value.codeFileUrl
    }
    // 收藏的公开模型
    if (formState.value.modelType === 1) {
      params.value.name = formState.value.name
      params.value.modelType = formState.value.modelType
      params.value.modelInfoId = formState.value.modelInfoIdFavorite
      params.value.dataIdList = formState.value.dataIdList
      params.value.normDetailsIdList = formState.value.normDetailsIdList
    }
    try {
      await runAddDataCleaning(params.value, { isAddUid: true })

      message.success('操作成功')
      router.back()
    } catch (error) {
      console.log('---', error)
      if (error.code === 'ATP-100021') {
        router.back()
      }
    }
  }

  watch(
    () => formState.value.modelType,
    val => {
      formState.value.modelInfoId = ''
      formState.value.model = ''
      // 获取不同模型数据
      if (val === 0) {
        console.log('模型管理')
        getModelBaseList()
      } else if (val === 1) {
        console.log('我收藏的')
        // 获取收藏模型
        getModelFavoriteList()
      }
    }
  )

  // 初始化
  onMounted(() => {
    getModelBaseList()
    initFilerefixUrl()
    getNormDetailsOptions()
  })
</script>

<style lang="less" scoped>
  .edit-task {
    :deep(.ant-form-item) {
      margin-bottom: 40px;
    }

    :deep(.ant-form-item-label > label::after) {
      display: none;
    }

    :deep(.ant-radio-wrapper) {
      margin-right: 24px;
    }

    .ant-radio-wrapper :deep(.ant-transfer-list) {
      position: relative;

      .ant-transfer-list-header {
        height: 39px;
        background: #fafafa;
      }

      &:first-child {
        .ant-transfer-list-header {
          &::after {
            content: '待选';
            position: absolute;
            right: 8px;
          }
        }
      }

      &:last-child {
        .ant-transfer-list-header {
          &::after {
            content: '已选';
            position: absolute;
            right: 8px;
          }
        }
      }

      .ant-input-affix-wrapper {
        height: 32px;
        min-height: 32px !important;
      }
    }

    .tag-select {
      display: flex;

      .left {
        margin-right: 80px;
      }
    }

    .model-select {
      display: flex;
      width: 100%;

      .a-select {
        // width: 214px;
      }
    }

    .upload-btn {
      color: @text02;

      img {
        padding-bottom: 4px;
        width: 14px;
        height: 14px;
        vertical-align: middle;
      }
    }
  }

  .scheme-wrap {
    display: flex;
    justify-content: space-between;
    gap: 0 40px;

    > div {
      width: 50%;
      border-radius: 2px;

      .option-wrap {
        display: flex;
        padding: 20px 24px;
        background: #fafafa;
        border-radius: 6px;
        flex-direction: column;
        gap: 24px 0;

        .option-input-wrap {
          display: flex;
          // align-items: center;
          font-size: 14px;
          color: rgba(25, 25, 48, 0.75);
          gap: 0 16px;
          font-weight: 400;
          line-height: 22px;

          > p {
            line-height: 32px;
          }

          :deep(.ant-form-item) {
            margin-bottom: 0;
          }
        }
      }
    }
  }
</style>
